package com.ruoyi.web.controller.net;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.net.constant.UdpConstants;
import com.ruoyi.net.domain.NetElement;
import com.ruoyi.net.domain.PerformanceListVo;
import com.ruoyi.net.service.INetElementService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.net.domain.Performance;
import com.ruoyi.net.service.IPerformanceService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 性能管理-性能Controller
 * 
 * @author tony
 * @date 2024-12-19
 */
@Api(tags = "性能管理-性能")
@RestController
@RequestMapping("/performance/performance")
public class PerformanceController extends BaseController
{
    @Autowired
    private IPerformanceService performanceService;

    @Autowired
    private DatagramSocket socket;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private INetElementService netElementService;

    /**
     * 读取性能管理-性能列表
     */
    @ApiOperation(value = "读取性能管理-性能列表", httpMethod = "GET")
//    @PreAuthorize("@ss.hasPermi('net:performance:list')")
    @GetMapping("/send/{ip}")
    public AjaxResult send(@PathVariable("ip") String ip) {
        // 发送查询性能-WS向M查询某NE所有盘性能
        boolean isSend = sendQueryPerformance(ip);
        if (!isSend) {
            return AjaxResult.error("发送失败");
        }
        return AjaxResult.success();
    }

    private boolean sendQueryPerformance(String ip) {
        boolean isSend = true;
        byte sno = 0;
        try {
            InetAddress targetAddress = InetAddress.getByName(ip);
            // 要发送的数据
            sno = (byte) ThreadLocalRandom.current().nextInt(Byte.MAX_VALUE);

            // 性能数据 28 fos私有协议 + 21协议头 ,  JC0421 0xe,
            char[] pmBytes = {0x0, 0x0, 0x0, 0x1c, 0x0, 0x1, 0x0, 0x1, 0x0, 0x0, 0x0, 0x64, 0x46, 0x48, 0x4d, 0x50, 0x2, 0xe1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x11, 0x0, 0x0, 0x0, 0x54
                    , 0x4a, 0x43, 0x4, 0x21, 0x88, 0x0, 0x31, 0x0, 0x0, 0x81, 0x11, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3f
                    , 0x80, 0x1, 0xff, 0xff, 0xff, 0x0, 0x0, 0x0, 0x1, 0x0, 0xe, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x10, 0x0, 0x18, 0x80, 0x81, 0x4, 0x20, 0x1, 0x2a, 0x20, 0x8, 0x0, 0x10, 0x0, 0x18, 0xff, 0x1, 0x20, 0xcc, 0x99, 0xb3, 0xe6, 0xfc, 0xff, 0xff, 0xff, 0xff, 0x1, 0x2a, 0xc, 0xa, 0xa, 0x8, 0x2, 0x10, 0x4, 0x1a, 0x4, 0xff, 0xff, 0xff, 0xff, 0x32, 0x2, 0x31, 0x37};
            ByteBuffer bufferPm = ByteBuffer.allocate(pmBytes.length);
            for (int i = 0; i < pmBytes.length; i++) {
                if (i == 23 || i == 38) {
                    bufferPm.put(sno);
                } else {
                    bufferPm.put((byte) pmBytes[i]);
                }
            }
            bufferPm.flip();
            byte[] sendDataPm = bufferPm.array();
            // fos 28
            // 协议头21字节
            // 15字节
            DatagramPacket sendPacketPm = new DatagramPacket(sendDataPm, sendDataPm.length, targetAddress, UdpConstants.UDP_PORT);
            socket.send(sendPacketPm);
//            logger.info("查询性能数据已发送");
        } catch (Exception e) {
            logger.info("查询性能数据发送失败：" + e.getMessage());
            isSend = false;
        }
        return isSend;
    }

    /**
     * 读取性能管理-性能列表
     */
    @ApiOperation(value = "读取性能管理-性能列表", httpMethod = "GET")
//    @PreAuthorize("@ss.hasPermi('net:performance:list')")
    @GetMapping("/read")
    public TableDataInfo read(Performance performance)
    {
        startPage();
        List<PerformanceListVo> list = new ArrayList<>();
        return getDIYPageTable(list);
    }

    /**
     * 查询性能管理-性能列表
     */
    @ApiOperation(value = "查询性能管理-性能列表", httpMethod = "GET")
//    @PreAuthorize("@ss.hasPermi('net:performance:list')")
    @GetMapping("/list")
    public TableDataInfo list(Performance performance)
    {
        boolean isSend = 1 == Convert.toInt(ServletUtils.getParameter(TableSupport.PAGE_NUM), 1);

        startPage();
        // 第一页的时候发送性能查询命令
        if (isSend && StringUtils.isNotEmpty(performance.getElementId())) {
            NetElement netElement = netElementService.getCacheObject(performance.getElementId().replaceAll(CacheConstants.NET_ELEMENT_KEY, ""));
            sendQueryPerformance(netElement.getIp());
        }
        startPage();
        List<PerformanceListVo> list = performanceService.selectPerformanceList(performance);
        return getDataTable(list);
    }

    /**
     * 导出性能管理-性能列表
     */
    @ApiOperation(value = "导出性能管理-性能列表", httpMethod = "POST")
    @PreAuthorize("@ss.hasPermi('net:performance:export')")
    @Log(title = "性能管理-性能", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Performance performance)
    {
        List<PerformanceListVo> list = performanceService.selectPerformanceList(performance);
        ExcelUtil<PerformanceListVo> util = new ExcelUtil<PerformanceListVo>(PerformanceListVo.class);
        util.exportExcel(response, list, "性能管理-性能数据");
    }

    /**
     * 获取性能管理-性能详细信息
     */
    @ApiOperation(value = "获取性能管理-性能详细信息", httpMethod = "GET")
//    @PreAuthorize("@ss.hasPermi('net:performance:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(performanceService.selectPerformanceById(id));
    }

    /**
     * 新增性能管理-性能
     */
    @ApiOperation(value = "新增性能管理-性能", httpMethod = "POST")
    @PreAuthorize("@ss.hasPermi('net:performance:add')")
    @Log(title = "性能管理-性能", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Performance performance)
    {
        return toAjax(performanceService.insertPerformance(performance));
    }

    /**
     * 修改性能管理-性能
     */
    @ApiOperation(value = "修改性能管理-性能", httpMethod = "PUT")
//    @PreAuthorize("@ss.hasPermi('net:performance:edit')")
    @Log(title = "性能管理-性能", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Performance performance)
    {
        return toAjax(performanceService.updatePerformance(performance));
    }

    /**
     * 删除性能管理-性能
     */
    @ApiOperation(value = "删除性能管理-性能", httpMethod = "DELETE")
//    @PreAuthorize("@ss.hasPermi('net:performance:remove')")
    @Log(title = "性能管理-性能", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(performanceService.deletePerformanceByIds(ids));
    }
}
